package com.noahsloan.nutils.streams;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;

/**
 * InputStream that wraps a channel.
 * 
 * @author noah
 * 
 */
public class ChannelInputStream extends InputStream {

    private final ReadableByteChannel channel;

    private ByteBuffer one;

    public ChannelInputStream(final ReadableByteChannel channel) {
        super();
        this.channel = channel;
        one = ByteBuffer.allocate(1);
    }

    @Override
    public int read() throws IOException {
        int read = channel.read(one);
        one.flip();
        if (read == -1) {
            return -1;
        } else {
            byte b = one.get();
            one.flip();
            return b;
        }
    }

    @Override
    public int read(byte[] b) throws IOException {
        return channel.read(ByteBuffer.wrap(b));
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        return channel.read(ByteBuffer.wrap(b, off, len));
    }

    @Override
    public void close() throws IOException {
        channel.close();
    }

}
